package com.hd.quartz.util;

import com.hd.quartz.exception.RRException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * <h3>partitionjob</h3>
 * <p>ScheduleRunnable</p>
 *
 * @author : hduong
 * @version : 1.0
 * @date : 2020-09-11 16:38
 **/
public class ScheduleRunnable implements Runnable {

    /**
     * 代理 目标对象
     */
    private Object target;
    /**
     * 代理 目标对象 的 方法
     */
    private Method method;

    /**
     * 方法参数
     */
    private String params;

    /**
     * 方法参数数组
     */
    private Object[] paramss;


    public ScheduleRunnable(String beanName, String methodName, String params) throws NoSuchMethodException {
        this.target = SpringContextUtil.getBean(beanName);
        this.params = params;

        if(StringUtils.isNotBlank(params)){
            this.method = target.getClass().getDeclaredMethod(methodName, String.class);
        } else {
            this.method = target.getClass().getDeclaredMethod(methodName);
        }
    }



    @Override
    public void run() {
        try {
            ReflectionUtils.makeAccessible(method);
            if(StringUtils.isNotBlank(params)) {
                method.invoke(target, params);
            } else {
                method.invoke(target);
            }
        } catch (Exception e) {
            throw new RRException("执行定时任务失败: {}", e);
        }
    }
}
